<?php

class User_CharacterController extends Pldkp_Controller_Action
{
    
    public function indexAction()
    {
        //gets the user from the registry
        $user = Zend_Registry::getInstance()->user;
        if (!$user) throw new Pldkp_Controller_Exception_NoUser();
        
        //gets all the characters that belongs to the user
        $characters = $user->findDependentRowset('User_Model_Characters','User');
        
        
        $charactersResult = array();
        foreach ($characters as $char){
            $charactersResult[$char->id] = array(
                'name'  => $char->name,
                'class' => $char->findParentRow('User_Model_Classes','Classes')->name,
                'roles' => $char->getRaiderRanks()
            );
        }
        $this->view->characters = $charactersResult;
    }
    
    /**
     * Creates a character and the associated CharactersRolesRaiderRanks
     * @return void
     */
    public function createAction()
    {
        $user = Zend_Registry::getInstance()->user;
        if (!$user) throw new Pldkp_Controller_Exception_NoUser();
        
        $form = new User_Form_CreateCharacter();
        
        if ($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if ($form->isValid($formData)) {

                //Creating the character and inserting it into Characters()
                $character = new User_Model_Characters();
                $classID = $this->_request->getParam('class');
                $data = array(
                    'user_id'   => $user->id,
                    'name'      => $this->_request->getParam('name'),
                    'class_id'  => $classID,
                );
                $characterID = $character->insert($data);

                
                //Getting roles of the relevant class in order to
                //populate the CharactersRolesRaiderRanks
                $row = User_Model_Classes::getById($classID); 
                $roles = $row->findManyToManyRowset('User_Model_Roles','User_Model_ClassesRoles','Classes','Roles');
                
                $charactersRolesRaiderRanksTable = new User_Model_CharactersRolesRaiderRanks();
                foreach ($roles as $role) {
                    $roleData = array(
                        'character_id'  => $characterID,
                        'role_id'       => $role->role_id, 
                    );  
                    $charactersRolesRaiderRanksTable->insert($roleData);
                }
                $this->setFlashMessage('Character ' . $this->_request->getParam('name') . ' has been created!');
                $this->_redirect('/user/character/');                
                
            } else {
                $form->populate($formData);
            }
        }
        
        $this->view->form = $form;
    }
}